package com.xuan.juc.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;

public class CasDemo {
    // 比较并交换
    public static void main(String[] args) {
//        AtomicInteger atomicInteger =  new AtomicInteger(2021);

//        // CAS 是CPU的并发原语!
//        System.out.println(atomicInteger.compareAndSet(2021, 2022));
//        System.out.println(atomicInteger.get());
//
////        -------------------------捣乱线程-------------------
//        System.out.println(atomicInteger.compareAndSet(2022, 2021));
//        System.out.println(atomicInteger.get());
////        -------------------------捣乱线程-------------------
//
//
//        System.out.println(atomicInteger.compareAndSet(2021, 6666));
//        System.out.println(atomicInteger.get());

//        如果泛型是包装类 注意对象的引用问题 Integer -128~127
        AtomicStampedReference<Integer> integerAtomicStampedReference = new AtomicStampedReference<>(10, 1);

        new Thread(()->{
            int stamp = integerAtomicStampedReference.getStamp(); // 获取版本号
            System.out.println(stamp);


            System.out.println(integerAtomicStampedReference.compareAndSet(10, 33,
                    integerAtomicStampedReference.getStamp(), integerAtomicStampedReference.getStamp() + 1));

            System.out.println("a=>"+integerAtomicStampedReference.getStamp());

            System.out.println(integerAtomicStampedReference.compareAndSet(33, 10,
                    integerAtomicStampedReference.getStamp(), integerAtomicStampedReference.getStamp() + 1));

            System.out.println("a=>"+integerAtomicStampedReference.getStamp());
        },"a").start();


        new Thread(()->{

            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            int stamp = integerAtomicStampedReference.getStamp(); // 获取版本号
            System.out.println("B=>"+integerAtomicStampedReference.getStamp());


            System.out.println(integerAtomicStampedReference.compareAndSet(10, 66,
                    integerAtomicStampedReference.getStamp(), integerAtomicStampedReference.getStamp() + 1));

            System.out.println("B=>"+integerAtomicStampedReference.getStamp());
        },"B").start();
    }
}
